package cn.yuhh.api.v1.user;

import cn.yuhh.api.exception.ApiException;
import cn.yuhh.api.helper.ApiResponse;
import cn.yuhh.api.service.AbstractApiService;
import cn.yuhh.core.annotation.NotNull;
import cn.yuhh.core.domain.User;
import cn.yuhh.core.type.ResponseHeader;
import cn.yuhh.core.util.DigestUtils;
import cn.yuhh.core.util.UUIDGenerator;
import com.magic.spring.mongo.Mongo;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @author ysw
 * @create 2020-02-18 15:32
 * @descreption
 **/
@Component("register1.0")
@NotNull(name = {"name","tel","addr","password"})
public class RegisterService extends AbstractApiService {
    @Override
    public Map service(Map request) {
        User user = map2bean(User.class,request);
        String confirmPassword = string(request, "confirmPassword");
        if(!confirmPassword.equals(user.getPassword())){
            throw new ApiException(ResponseHeader.CONFIRM_PASSWORD_ERROR);
        }
        if(Mongo.buildMongo().eq("name",user.getName()).count(User.class)>0){
            throw new ApiException(ResponseHeader.USER_NAME_HAS);
        }
        user.setPassword(DigestUtils.MD5(user.getPassword()));
        Mongo.buildMongo().insert(user);
        String sessionId = UUIDGenerator.uuid();
        sessionManager.put(user.getId(), sessionId);
        return ApiResponse.success(new HashMap(){{
            put("id", user.getId());
            put("name", user.getName());
            put("tel", user.getTel());
            put("sessionId", sessionId);
            put("role", user.getRole());
        }});
    }
}